package com.bstek.uflo.form.command;

import org.hibernate.Query;
import org.hibernate.Session;

import com.bstek.dorado.data.provider.Page;
import com.bstek.uflo.command.Command;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.form.model.TableDefinition;

/**
 * @author Jacky.gao
 * @since 2013年11月7日
 */
public class QueryTableCommand implements Command<Object> {
	private Long parentId;
	private Page<TableDefinition> page;
	public QueryTableCommand(Page<TableDefinition> page,Long parentId){
		this.page=page;
		this.parentId=parentId;
	}
	@SuppressWarnings("unchecked")
	public Object execute(Context context) {
		Query query=null;
		String hql="from "+TableDefinition.class.getName()+"";
		int count=0;
		Session session=context.getSession();
		if(parentId!=null && parentId>0){
			hql+=" where parentId=:parentId";
			query=session.createQuery(hql+" order by createDate desc");
			query.setLong("parentId", parentId);
			count=queryCount(session,hql);
		}else{
			hql+=" where parentId=0";
			query=session.createQuery(hql+" order by createDate desc");
			query=session.createQuery(hql);
			count=queryCount(session,hql);
		}
		query.setFirstResult((page.getPageNo()-1)*page.getPageSize());
		query.setMaxResults(page.getPageSize());
		page.setEntities(query.list());
		page.setEntityCount(count);
		return null;
	}
	private int queryCount(Session session,String hql){
		int count=0;
		Query countQuery=session.createQuery("select count(*) "+hql);
		if(parentId!=null && parentId>0){
			countQuery.setLong("parentId", parentId);
		}
		Object obj=countQuery.uniqueResult();
		if(obj==null){
			obj=0;
		}
		if(obj instanceof Integer){
			count=(Integer)obj;
		}else if(obj instanceof Long){
			count=((Long)obj).intValue();
		}else{
			throw new IllegalArgumentException("Query count was failed.");
		}
		return count;
	}
}
